package com.chenl.provider.util;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;

public class ListSplitUtils {
    //切割数组
    public static List<List<?>> splitList(List<?> lists, Integer groupCount) {
        List<List<?>> returnList=new ArrayList<>();
        List<?> list = lists.stream().collect(Collectors.toList());
        int size = list.size();
        if (CollectionUtils.isEmpty(list)){
            return returnList;
        }else if(size<=groupCount){
            returnList.add(list);
            return returnList;
        }else {
            Integer len;
            if (size%groupCount==0){
                len=size/groupCount;
            }else {
                len=size/groupCount+1;
            }
            int index=0;
            int lastIndex=groupCount;
            for (Integer i = 0; i < len; i++) {
                returnList.add(list.subList(index,lastIndex));
                index=lastIndex;
                lastIndex=i==len-2?size:lastIndex+groupCount;
            }
            return returnList;
        }
    }
    //分页工具
    public static List<?>  splitResultListByPage(List<?> list,String pageNumber,String pageSize){
        if (org.apache.commons.lang.StringUtils.isNotBlank(pageNumber)&& org.apache.commons.lang.StringUtils.isNotBlank(pageSize)) {
            Integer page = Integer.valueOf(pageNumber);
            Integer size = Integer.valueOf(pageSize);
            if (page<0||size<0){
                throw new RuntimeException("分页参数有误 : pageNumber:"+pageNumber+" pageSize:"+pageSize);
            }else if (page==0){
                list=new ArrayList<>();
            }else {
                list=list.stream().skip((page-1)*size).limit(size).collect(Collectors.toList());
            }
        }
        return list;
    }

}
